<template>
  <div>
    <table border="1" width="700" style="border-collapse: collapse">
      <caption>
        购物车
      </caption>
      <thead>
        <tr>
          <th><input type="checkbox" v-model="isAll" /> <span>全选</span></th>
          <th>名称</th>
          <th>价格</th>
          <th>数量</th>
          <th>总价</th>
          <th>操作</th>
        </tr>
      </thead>
      <WangTbody
        :goodList="goodList"
        @click="clickFn"
        @delItem="delFn"
        @jianFn="jianFn"
        @jiaFn="jiaFn"
      ></WangTbody>
      <TotalMoney :goodList="goodList"></TotalMoney>
    </table>
  </div>
</template>

<script>
import WangTbody from './components/WangTbody.vue'
import TotalMoney from './components/TotalMoney.vue'
export default {
  data() {
    return {
      goodList: JSON.parse(localStorage.getItem('goodList')) || [],
      /*  goodList: [
        {
          name: '诸葛亮',
          price: 1000,
          num: 1,
          checked: false,
        },
        {
          name: '蔡文姬',
          price: 1500,
          num: 1,
          checked: false,
        },
        {
          name: '妲己',
          price: 2000,
          num: 1,
          checked: false,
        },
        {
          name: '鲁班',
          price: 2200,
          num: 1,
          checked: false,
        },
      ], */
    }
  },
  components: {
    WangTbody,
    TotalMoney,
  },
  methods: {
    clickFn(name) {
      this.goodList.forEach((item) => {
        if (item.name == name) {
          !item.checked
        }
      })
    },
    delFn(name) {
      this.goodList = this.goodList.filter((item) => item.name !== name)
    },
    jianFn(name) {
      this.goodList.find((item) => {
        if (item.name == name) {
          item.num > 0 && item.num--
        }
      })
    },
    jiaFn(name) {
      this.goodList.find((item) => {
        if (item.name == name) {
          item.num++
        }
      })
    },
  },
  watch: {
    goodList: {
      handler() {
        localStorage.setItem('goodList', JSON.stringify(this.goodList))
      },
      deep: true,
    },
  },
  computed: {
    isAll: {
      get() {
        return this.goodList.every((item) => item.checked)
      },
      set(val) {
        //console.log(val)
        return this.goodList.forEach((item) => (item.checked = val))
      },
    },
  },
}
</script>

<style></style>
